//
//  PDScrollView.m
//  GiganticWhale
//
//  Created by GiganticWhale on 16/8/14.
//  Copyright © 2016年 Gigantic. All rights reserved.
//

#import "PDScrollView.h"
#import "GCD.h"

static char bannerTapKey;
@interface PDScrollView()<UIScrollViewDelegate>
@property (nonatomic,strong)UIScrollView *mainScrollView;       /**< 主scrollView*/
@property (nonatomic,strong)UIPageControl *pageControl;         /**< pageControl*/
@property (nonatomic,strong)GCDTimer *timer;                                    /**< */
@property (nonatomic,strong)PDImageView *currentImgView;        /**< 当前的图片*/
@property (nonatomic,strong)PDImageView *preImgView;            /**< 其他图片*/
@property (nonatomic,strong)PDImageView *nextImgView;           /**< 下一张*/
@property (nonatomic,assign)NSInteger currentIndex;             /**< 当前的index*/
@property (nonatomic,assign)NSInteger preIndex;
@property (nonatomic,assign)NSInteger nextIndex;
@property (nonatomic,assign)NSInteger timeCount;

@property (nonatomic,strong)PDImageView *shadowImgView;
@property (nonatomic,strong)UILabel *adLabel;                   /**< 广告label*/


@end


@implementation PDScrollView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        if (!self.mainScrollView){
            [self createView];
        }
    }
    return self;
}

-(void)createView{
    self.mainScrollView = [[UIScrollView alloc]init];
    self.mainScrollView.backgroundColor = [UIColor clearColor];
    self.mainScrollView.frame = self.bounds;
    self.mainScrollView.alwaysBounceVertical = NO;
    self.mainScrollView.alwaysBounceHorizontal = NO;
    self.mainScrollView.autoresizesSubviews = YES;
    self.mainScrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.mainScrollView.bounces = YES;
    self.mainScrollView.bouncesZoom = YES;
    self.mainScrollView.canCancelContentTouches = YES;
    self.mainScrollView.clearsContextBeforeDrawing = YES;
    self.mainScrollView.clipsToBounds = YES;
    self.mainScrollView.contentMode = UIViewContentModeScaleToFill;
    self.mainScrollView.delaysContentTouches = YES;
    self.mainScrollView.directionalLockEnabled = NO;
    self.mainScrollView.indicatorStyle = UIScrollViewIndicatorStyleDefault;
    self.mainScrollView.multipleTouchEnabled = YES;
    self.mainScrollView.opaque = YES;
    self.mainScrollView.pagingEnabled = YES;
    self.mainScrollView.scrollEnabled = YES;
    self.mainScrollView.showsHorizontalScrollIndicator = NO;
    self.mainScrollView.showsVerticalScrollIndicator = YES;
    self.mainScrollView.userInteractionEnabled = YES;
    self.mainScrollView.delegate = self;
    [self addSubview:self.mainScrollView];
    
    // 2. 创建 pageControl
    self.pageControl = [[UIPageControl alloc]init];
    self.pageControl.backgroundColor = [UIColor clearColor];
    [self.pageControl addTarget:self action:@selector(pageControlManager) forControlEvents:UIControlEventTouchUpInside];
    self.pageControl.frame = CGRectMake(LCFloat(11), self.size_height - LCFloat(20), LCFloat(100), LCFloat(20));
    [self addSubview:self.pageControl];
    
    // 4. 创建图片
    if (!self.currentImgView){
        self.currentImgView = [self createCustomerImgView];
        self.currentImgView.frame = CGRectMake(self.size_width, 0, self.size_width, self.size_height);
        self.currentImgView.userInteractionEnabled = YES;
    }
    
    if (!self.preImgView){
        self.preImgView = [self createCustomerImgView];
        self.preImgView.frame = CGRectMake(0, 0, self.size_width, self.size_height);
    }
    
    if (!self.nextImgView){
        self.nextImgView = [self createCustomerImgView];
        self.nextImgView.frame = CGRectMake(2 * self.size_width, 0, self.size_width, self.size_height);
    }
    
    // 3. 创建收拾
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageViewWithFocusImg)];
    [self.currentImgView addGestureRecognizer:tapGesture];
    
    // 5. 创建阴影
    self.shadowImgView = [[PDImageView alloc]init];
    self.shadowImgView.backgroundColor = [UIColor clearColor];
    self.shadowImgView.frame = CGRectMake(0, self.size_height - LCFloat(30), kScreenBounds.size.width, LCFloat(30));
    self.shadowImgView.image = [UIImage imageNamed:@"pro_bg_blackshadow"];
    [self addSubview:self.shadowImgView];
    
    // 5. 创建条目
    self.adLabel = [[UILabel alloc]init];
    self.adLabel.backgroundColor = [UIColor clearColor];
    self.adLabel.textAlignment = NSTextAlignmentRight;
    self.adLabel.textColor = [UIColor whiteColor];
    self.adLabel.shadowColor = [UIColor colorWithCustomerName:@"浅灰"];
    self.adLabel.shadowOffset = CGSizeMake(.4f, .4f);
    self.adLabel.font = [UIFont fontWithCustomerSizeName:@"提示"];
    self.adLabel.frame = CGRectMake(CGRectGetMaxX(self.pageControl.frame) + LCFloat(11), self.bounds.size.height - [NSString contentofHeightWithFont:self.adLabel.font] - LCFloat(5), kScreenBounds.size.width - LCFloat(11) - CGRectGetMaxX(self.pageControl.frame) - LCFloat(11), [NSString contentofHeightWithFont:self.adLabel.font]);
    [self addSubview:self.adLabel];
}

-(PDImageView *)createCustomerImgView{
    PDImageView *imageView = [[PDImageView alloc]init];
    imageView.autoresizesSubviews = YES;
    imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    
    imageView.clearsContextBeforeDrawing = YES;
    imageView.clipsToBounds = NO;
    imageView.contentMode = UIViewContentModeScaleToFill;
    imageView.highlighted = NO;
    imageView.multipleTouchEnabled = NO;
    imageView.opaque = YES;
    imageView.userInteractionEnabled = NO;
    [self.mainScrollView addSubview:imageView];
    return imageView;
}


-(void)setIsPageControl:(BOOL)isPageControl{
    _isPageControl = isPageControl;
    if (isPageControl){         // 显示
        self.pageControl.hidden = YES;
    } else {                    // 不显示
        self.pageControl.hidden = NO;
    }
}


-(void)setTransferImArr:(NSArray *)transferImArr{
    _transferImArr = [transferImArr copy];
    
    if (!self.transferImArr.count){
        return;
    }
    self.currentIndex = 0;
    
    // pageControl
    self.pageControl.numberOfPages = transferImArr.count;
    
    // scrollView
    self.mainScrollView.contentSize = CGSizeMake(transferImArr.count * self.size_width, self.size_height);
    // setting imgs
    [self doWithImgView];
    
//    // 启动计时器
    if (!self.timer) {
        [self startTimer];
    }
}

- (void)doWithImgView{
    self.preIndex = (self.currentIndex - 1 + self.transferImArr.count) % self.transferImArr.count ;
    self.nextIndex = (self.currentIndex + 1 + self.transferImArr.count) % self.transferImArr.count;
    
    // current
    GWScrollViewSingleModel *scrollViewSingleModel1 = [self.transferImArr objectAtIndex:self.currentIndex];
    [self.currentImgView uploadImageWithURL:scrollViewSingleModel1.img placeholder:nil callback:NULL];
    self.adLabel.text = scrollViewSingleModel1.content;
    
    // pre
    GWScrollViewSingleModel *scrollViewSingleModel2 = [self.transferImArr objectAtIndex:self.preIndex];
    [self.preImgView uploadImageWithURL:scrollViewSingleModel2.img placeholder:nil callback:NULL];
    
    // next
    GWScrollViewSingleModel *scrollViewSingleModel3 = [self.transferImArr objectAtIndex:self.nextIndex];
    [self.nextImgView uploadImageWithURL:scrollViewSingleModel3.img placeholder:nil callback:NULL];
    
}

#pragma mark - Action
-(void)startTimer{
    // timer
    __weak typeof(self) weakSelf = self;
    self.timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [self.timer event:^{
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf doAction];
    } timeIntervalWithSecs:6 delaySecs:1.f];
    [self.timer start];
}


#pragma mark - Action
-(void)startTimerWithTime:(NSInteger)time{
    self.timeCount = time;
    [self removeTimer];

    // timer
    __weak typeof(self) weakSelf = self;
    self.timer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    [self.timer event:^{
        if (!weakSelf){
            return ;
        }
        __strong typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf doAction];
    } timeIntervalWithSecs:time delaySecs:1.f];
    [self.timer start];
}


-(void)removeTimer{
    if (!self.timer){
        return;
    }
    [self.timer destroy];
    self.timer = nil;
}

-(void)pageControlManager{
    [self removeTimer];
    
    self.currentIndex = self.pageControl.currentPage;
    
    // 设置图片
    [self doWithImgView];
    
    // 重新启动
    [self startTimer];
}

-(void)tapImageViewWithFocusImg{
    void(^block)(GWScrollViewSingleModel *) = objc_getAssociatedObject(self, &bannerTapKey);
    GWScrollViewSingleModel *scrollViewSingleModel = [self.transferImArr objectAtIndex:self.currentIndex];
    if (block){
        block(scrollViewSingleModel);
    }
}

#pragma makr  执行操作
-(void)doAction{
    self.currentIndex = (self.currentIndex + 1 + self.transferImArr.count) % self.transferImArr.count;
    
    // 设置图片
    [self doWithImgView];
    if (self.transferImArr.count > 1){
        // add Animation
        [self addAnimationView:self.currentImgView WithType:@"rippleEffect" subType:kCATransitionFromLeft duration:.5f];
    }
    self.mainScrollView.contentOffset = CGPointMake(self.size_width, 0);
    self.pageControl.currentPage = self.currentIndex;
}

-(void)tapManager{
    
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{     // 开始拖拽，移除计时器
    [self removeTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGFloat offX = self.mainScrollView.contentOffset.x;
    // 偏移了
    if (offX  > self.mainScrollView.size_width) {           // 向左滚动
        self.currentIndex = (self.currentIndex + 1 + self.transferImArr.count) % self.transferImArr.count;
    }else if(offX  < self.size_width){
        // 往右
        self.currentIndex = (self.currentIndex - 1 + self.transferImArr.count) % self.transferImArr.count;
    }
    
    // 设置图片
    [self doWithImgView];
    
    self.mainScrollView.contentOffset = CGPointMake(self.size_width, 0);
    self.pageControl.currentPage = self.currentIndex;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{        // 拖拽结束，重启timer
    [self startTimer];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
}


#pragma mark - Animation
#pragma mark - 过渡动画
- (void)addAnimationView:(UIView *)view WithType:(NSString *)type subType:(NSString *)subType duration:(CGFloat)duration{
    CATransition *transition = [CATransition animation];
    transition.subtype = subType;
    transition.type = type;
    transition.duration = duration;
    [view.layer addAnimation:transition forKey:@"layerAnimation"];
}

- (void)removeAnimationView:(UIView *)view{
    [view.layer removeAnimationForKey:@"layerAnimation"];
}

-(void)bannerImgTapManagerWithInfoblock:(void(^)(GWScrollViewSingleModel *))block{
    objc_setAssociatedObject(self, &bannerTapKey, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}



@end
